package com.sgu6.sgu6_machine.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.event.WarningEvent;
import com.sgu6.middleware.util.AppUtils;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.netty.container.Machine;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.adapter.ControlAdapter;
import com.sgu6.sgu6_machine.adapter.MachineCmdAdapter;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.common.CmdTranslator;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.db.DBManager;
import com.sgu6.sgu6_machine.dto.AppUpdateDto;
import com.sgu6.sgu6_machine.dto.MachineCmdDto;
import com.sgu6.sgu6_machine.event.AppUpdateEvent;
import com.sgu6.sgu6_machine.event.CmdEvent;
import com.sgu6.sgu6_machine.event.ExitTimeEvent;
import com.sgu6.sgu6_machine.event.PowerEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.ui.fragment.set.AccuracyF;
import com.sgu6.sgu6_machine.ui.fragment.set.CoherentActionF;
import com.sgu6.sgu6_machine.ui.fragment.set.DoorSetF;
import com.sgu6.sgu6_machine.ui.fragment.set.GarnerF;
import com.sgu6.sgu6_machine.ui.fragment.set.MachineTestF;
import com.sgu6.sgu6_machine.ui.fragment.set.MillSetF;
import com.sgu6.sgu6_machine.ui.fragment.set.ModeF;
import com.sgu6.sgu6_machine.ui.fragment.set.MotorF;
import com.sgu6.sgu6_machine.ui.fragment.set.PowerF;
import com.sgu6.sgu6_machine.ui.fragment.set.TemperatureF;
import com.sgu6.sgu6_machine.ui.fragment.set.ViolenceF;
import com.sgu6.sgu6_machine.ui.fragment.set.WarningF;
import com.sgu6.sgu6_machine.ui.fragment.set.WeightF;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachineManagerA extends BaseA implements ControlAdapter.OnItemControlClickListener, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.rvMachineCmd)
    RecyclerView rvMachineCmd;
    @BindView(R.id.rvControl)
    RecyclerView rvControl;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tvWorkStatus)
    TextView tvWorkStatus;
    @BindView(R.id.tvWarnStatus)
    TextView tvWarnStatus;
    @BindView(R.id.cmdSwitch)
    Switch cmdSwitch;
    @BindView(R.id.tvAppVersion)
    TextView tvAppVersion;
    @BindView(R.id.etCommand)
    EditText etCommand;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.iv_update_app)
    ImageView ivUpdateApp;
    @BindView(R.id.labelWarn)
    TextView labelWarn;
    @BindView(R.id.btnSend)
    Button btnSend;
    @BindView(R.id.container)
    FrameLayout container;


    private List<String> controlNames;

    private List<MachineCmdDto> cmdDtoList;
    private MachineCmdAdapter adapter;
    private CmdTranslator mp = new CmdTranslator();
    private boolean isFilter = false;//是否过滤心跳信息

    private FragmentManager fm;
    private FragmentTransaction ft;
    private Fragment powerF, garnerF, accuracyF, motorF, millSetF, temperatureF, warningF, weightF, machineTestF, doorSetF, modeF, violenceF, coherentActionF;

    private MachineP machineP = new MachineP();

    public CountDownTimer timer;
    public boolean isTimerRunning = false;

    private AppUpdateDto appUpdateDto;
    private Map<String, Fragment> fragmentMap = new HashMap<>();

    @SuppressLint("MissingSuperCall")
    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_machine_manager);
        ButterKnife.bind(this);

        initUI();

    }




    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
        timer.cancel();
        if (timer != null) {
            timer = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initUI() {
        initToolbar();
        initCountDownTimer();
        initData();
        initParams();
        initFragments();
        checkNewVersion();
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
    }

    private void checkNewVersion() {
//        machineP.getLastAppList(1, 3, 1);
    }


    private void initParams() {
        cmdDtoList = new ArrayList<>();
        mp = new CmdTranslator();
        adapter = new MachineCmdAdapter(cmdDtoList);
        rvMachineCmd.setLayoutManager(new LinearLayoutManager(this));
        rvMachineCmd.setAdapter(adapter);


        ControlAdapter controlAdapter = new ControlAdapter(controlNames);
        controlAdapter.setOnClickListener(this);
        rvControl.setLayoutManager(new LinearLayoutManager(this));
        rvControl.setAdapter(controlAdapter);

        tvAppVersion.setText("应用版本号N:".concat(AppUtils.getVersionInfo(this)));


        cmdSwitch.setOnCheckedChangeListener(this);
    }

    private void initToolbar() {
        toolbar.setBackgroundResource(R.color.colorPrimaryDark);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    public void initCountDownTimer() {
        runOnUiThread(() -> {
            timer = new CountDownTimer(MachineContainer.machineConfigDto.exitSetTime * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    stopTimer();
                    MachineManagerA.this.finish();
                }
            };
            timer.start();
            isTimerRunning = true;
        });
    }

    public void resetTimer(int time) {
        if (timer != null) {
            timer.cancel();
            isTimerRunning = false;
        }
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                stopTimer();
                MachineManagerA.this.finish();
            }
        };
        timer.start();
        isTimerRunning = true;
    }

    /**
     * 开始计时显示内容细节
     */
    public void startTimer() {
        if (!isTimerRunning) {
            timer.start();
            isTimerRunning = true;
        }
    }

    /**
     * 停止计时显示内容
     */
    public void stopTimer() {
        if (isTimerRunning) {
            timer.cancel();
            isTimerRunning = false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_set, menu);
        return true;
    }

    private void initFragments() {
        if (garnerF == null) {
            garnerF = GarnerF.newInstance();
            fragmentMap.put("谷仓设置", garnerF);
        }
        if (millSetF == null) {
            millSetF = MillSetF.newInstance();
            fragmentMap.put("碾米设置", millSetF);
        }


        if (accuracyF == null) {
            accuracyF = AccuracyF.newInstance();
            fragmentMap.put("精度设置", accuracyF);
        }

        if (motorF == null) {
            motorF = MotorF.newInstance();
            fragmentMap.put("电机设置", motorF);
        }

        if (temperatureF == null) {
            temperatureF = TemperatureF.newInstance();
            fragmentMap.put("温度设置", temperatureF);
        }

        if (warningF == null) {
            warningF = WarningF.newInstance();
            fragmentMap.put("警报设置", warningF);
        }

        if (weightF == null) {
            weightF = WeightF.newInstance();
            fragmentMap.put("重量设置", weightF);
        }

        if (machineTestF == null) {
            machineTestF = MachineTestF.newInstance();
            fragmentMap.put("机器测试", machineTestF);
        }

        if (doorSetF == null) {
            doorSetF = DoorSetF.newInstance();
            fragmentMap.put("开关门设置", doorSetF);
        }

        if (modeF == null) {
            modeF = ModeF.newInstance();
            fragmentMap.put("模式设置", modeF);
        }

        if (violenceF == null) {
            violenceF = ViolenceF.newInstance();
            fragmentMap.put("暴力测试", violenceF);
        }

        if (coherentActionF == null) {
            coherentActionF = CoherentActionF.newInstance();
            fragmentMap.put("连贯测试", coherentActionF);
        }

        if (powerF == null) {
            powerF = PowerF.newInstance();
            fragmentMap.put("电量管理", powerF);
        }


        fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        ft.add(R.id.container, machineTestF);
        ft.add(R.id.container, millSetF);
        ft.add(R.id.container, accuracyF);
        ft.add(R.id.container, garnerF);
        ft.add(R.id.container, motorF);
        ft.add(R.id.container, temperatureF);
        ft.add(R.id.container, warningF);
        ft.add(R.id.container, weightF);
        ft.add(R.id.container, doorSetF);
        ft.add(R.id.container, modeF);
        ft.add(R.id.container, violenceF);
        ft.add(R.id.container, coherentActionF);
        ft.add(R.id.container, powerF);

        ft.hide(millSetF);
        ft.hide(accuracyF);
        ft.hide(garnerF);
        ft.hide(motorF);
        ft.hide(temperatureF);
        ft.hide(warningF);
        ft.hide(weightF);
        ft.hide(doorSetF);
        ft.hide(modeF);
        ft.hide(violenceF);
        ft.hide(coherentActionF);
        ft.hide(powerF);

        ft.commit();
    }


    private void initData() {
        controlNames = new ArrayList<>();
        controlNames.add("机器测试");
        controlNames.add("碾米设置");
        controlNames.add("精度设置");
        controlNames.add("重量设置");
        controlNames.add("电机设置");
        controlNames.add("警报设置");
        controlNames.add("电量管理");
//        controlNames.add("模式设置");

        if (MachineContainer.machineConfigDto.withPack) {
            controlNames.add("温度设置");
        }
        if (!MachineContainer.machineConfigDto.withPack) {
            controlNames.add("谷仓设置");
            controlNames.add("开关门设置");
        }
        if (MachineContainer.machineConfigDto.merchantId.equals(Constant.SGU6_MERCHANT_ID)) {
            controlNames.add("暴力测试");
            controlNames.add("连贯测试");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExitTimeEvent(ExitTimeEvent event) {
        if (event.isExit) {
            resetTimer(event.exitTime);
        }
    }

    @SuppressLint("DefaultLocale")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCmdEvent(CmdEvent event) {

        if (event.type == 1) {
            switch (event.cmd[5]) {
                case 0x02:
                    String workStatus = "";
                    HashMap<String, Long> status = mp.translateHeart2Map(HexUtil.Bytes2HexString(event.cmd));
                    if (MachineContainer.machineConfigDto.withPack) {
                        workStatus = String.format("横封温度:%s℃，纵封温度:%s℃，", String.format("%.1f", status.get("hTemp") * 0.1), String.format("%.1f", status.get("vTemp") * 0.1));
                    }
                    workStatus = String.format("%s整机工作状态:%s，重量:%d克，电流:%sA \n输出状况:%s\n接近开关状况:%s", workStatus, mp.analyMainStatusValue(status), status.get("weight"), String.format("%.1f", status.get("electricity") * 0.1), mp.analysisOutStatusValue(status.get("outStatus")), mp.analySwitchStatusValue(status.get("switchStatus")));
                    tvWorkStatus.setText(workStatus);
//                    if (mp.analyseWarnValue(status.get("warnValue")).equals("")) {
//                        EventBus.getDefault().post(new WarningEvent(false, ""));
//                    }
                    break;
                case 0x05:
                    if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("上电");
                    } else if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("复位");
                    } else if (event.cmd[7] == 0x02) {
                        tvWorkStatus.setText("待机");
                    } else if (event.cmd[7] == 0x03) {
                        if (event.cmd[9] == 0x01) {
                            tvWorkStatus.setText("碾米中，调节精度");
                        } else if (event.cmd[9] == 0x02) {
                            tvWorkStatus.setText("碾米中，碾米");
                        } else if (event.cmd[9] == 0x03) {
                            tvWorkStatus.setText("碾米中，下米");
                        } else if (event.cmd[9] == 0x04) {
                            tvWorkStatus.setText("碾米中，拉膜");
                        } else if (event.cmd[9] == 0x05) {
                            tvWorkStatus.setText("碾米中，封膜");
                        } else if (event.cmd[9] == 0x06) {
                            tvWorkStatus.setText("碾米中，出货");
                        }
                    }
                    break;
                case 0x06:
                    String warnStatus = mp.analyseWarnValue((long) ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)));
                    tvWarnStatus.setText(warnStatus);
                    break;
                case 0x07:
                    warnStatus = mp.analySwitchStatusValue((long) ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)));
                    tvWarnStatus.setText(warnStatus);
                    break;
                case 0x0A:
                    EventBus.getDefault().post(new PowerEvent(1, event.cmd));
                    byte[] v = new byte[4];
                    System.arraycopy(event.cmd, 6, v, 0, 4);
                    int voltage = HexUtil.byteToInt2(v);
                    String warn1 = "电压：" + voltage * 0.0001f + "V";
                    tvWorkStatus.setText(warn1);
                    v = null;
                    break;
                case 0x0B:
                    EventBus.getDefault().post(new PowerEvent(2, event.cmd));
                    byte[] e = new byte[4];
                    System.arraycopy(event.cmd, 6, e, 0, 4);
                    int electric = HexUtil.byteToInt2(e);
                    String warn2 = "电流：" + electric * 0.0001f + "A";
                    tvWorkStatus.setText(warn2);
                    e = null;
                    break;
                case 0x0C:
                    EventBus.getDefault().post(new PowerEvent(3, event.cmd));
                    byte[] c = new byte[4];
                    System.arraycopy(event.cmd, 6, c, 0, 4);
                    int charge = HexUtil.byteToInt2(c);
                    String warn3 = "功率：" + charge * 0.0001f + "W";
                    tvWorkStatus.setText(warn3);
                    c = null;
                    break;
                case 0x0D:
                    EventBus.getDefault().post(new PowerEvent(4, event.cmd));
                    byte[] p = new byte[4];
                    System.arraycopy(event.cmd, 6, p, 0, 4);
                    int power = HexUtil.byteToInt2(p);
                    String warn4 = "电量：" + power * 0.0001f + "KWh";
                    tvWorkStatus.setText(warn4);
                    p = null;
                    break;
                case 0x0E:
                    byte[] p1 = new byte[4];
                    System.arraycopy(event.cmd, 6, p1, 0, 4);
                    int power1 = HexUtil.byteToInt2(p1);
                    String warn5 = "功率因素：" + power1 * 0.0001f + "KWh";
                    tvWorkStatus.setText(warn5);
                    p1 = null;
                    break;
                case 0x10:
                    warnStatus = mp.analyseWarnValue((long) event.cmd[9]);
                    tvWarnStatus.setText(mp.protocols.get(0x10) + ": " + warnStatus + "s");
                    break;
                case 0x11:
                    int hTemp = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText(mp.protocols.get(0x11) + ": " + hTemp);
                    break;
                case 0x12:
                    int vTemp = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText(mp.protocols.get(0x12) + ": " + vTemp);
                    break;
                case 0x13:
                    int oTemp = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText(mp.protocols.get(0x13) + ": " + oTemp);
                    break;
                case 0x14:
                    int sTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText(mp.protocols.get(0x14) + ": " + sTime + "s");
                    break;
                case 0x15:
                    int oWeight = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x15) + ": " + oWeight + "g");
                    break;
                case 0x48:
                    int checkWeight = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x48) + ": " + checkWeight + "克");
                    break;
                case 0x16:
                    int oneLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x16) + ": " + oneLayer + "步");
                    break;
                case 0x17:
                    int twoLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x17) + ": " + twoLayer + "步");
                    break;
                case 0x18:
                    int threeLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x18) + ": " + threeLayer + "步");
                    break;
                case 0x19:
                    int fourLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x19) + ": " + fourLayer + "步");
                    break;
                case 0x1A:
                    int fiveLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1A) + ": " + fiveLayer + "步");
                    break;
                case 0x1B:
                    int sixLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1B) + ": " + sixLayer + "步");
                    break;
                case 0x1C:
                    int sevenLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1C) + ": " + sevenLayer + "步");
                    break;
                case 0x1D:
                    int eightLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1D) + ": " + eightLayer + "步");
                    break;
                case 0x1E:
                    int nineLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1E) + ": " + nineLayer + "步");
                    break;
                case 0x1F:
                    int tenLayer = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText(mp.protocols.get(0x1F) + ": " + tenLayer + "步");
                    break;

                case 0x20:
                    if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("自动送谷模式");
                    } else {
                        tvWorkStatus.setText("不自动送谷模式");
                    }

                    break;
                case 0x21:
                    if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("关闭开关门模式");
                    } else {
                        tvWorkStatus.setText("打开开关门模式");
                    }
                    break;
                case 0x22:
                    if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("关闭电子锁模式");
                    } else {
                        tvWorkStatus.setText("打开电子锁模式");
                    }
                    break;
                case 0x25:
                    int dropDelay = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定下米延迟警报值(" + dropDelay + ")");
                    break;
                case 0x26:
                    int pullDelay = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定拉膜延迟警报值(" + pullDelay + ")");
                    break;
                case 0x27:
                    int sealDelay = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定封膜延迟警报值(" + sealDelay + ")");
                    break;
                case 0x63:
                    int pullMillTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定下米超时警报值(" + pullMillTime + ")");
                    break;
                case 0x64:
                    int pullMoTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定拉膜超时警报值(" + pullMoTime + ")");
                    break;
                case 0x65:
                    int sealMoTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定封膜超时警报值(" + sealMoTime + ")");
                    break;
                case 0x66:
                    int openDoorTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定开门超时警报值(" + openDoorTime + ")");
                    break;
                case 0x67:
                    int closeDoorTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定关门超时警报值(" + closeDoorTime + ")");
                    break;
                case 0x69:
                    int sendValleyTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定送谷超时警报值(" + sendValleyTime + ")");
                    break;
                case 0x6A:
                    int sendMoTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定送膜超时警报值(" + sendMoTime + ")");
                    break;
                case 0x6B:
                    int mexSteps = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff));
                    tvWorkStatus.setText("设定精度电机最大复位步数(" + mexSteps + ")");
                    break;
                case 0x6C:
                    int branFullTime = ((event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff)) / 10;
                    tvWorkStatus.setText("设定糠满超时警报值(" + branFullTime + ")");
                    break;
                case 0x41:
                    tvWorkStatus.setText("系统复位");
                    break;
                case 0x42:
                    tvWorkStatus.setText("系统重启");
                    break;
                case 0x43:
                    int layer = (event.cmd[9] & 0xff);
                    tvWorkStatus.setText("配置精度: " + layer + "分度");
                    break;
                case 0x44:
                    int packageWeight = (event.cmd[8] & 0xff) * 16 * 16 + (event.cmd[9] & 0xff);
                    tvWorkStatus.setText("碾米" + event.cmd[7] + "包,每包(" + packageWeight + "g)");
                    break;
                case 0x45:
                    int packages = event.cmd[7] & 0xff;
                    tvWorkStatus.setText("打包装(" + packages + ")");
                    break;
                case 0x46:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("停止当前工作并待机");
                        tvWarnStatus.setText("无");
                        EventBus.getDefault().post(new WarningEvent(false, ""));
                        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
                    } else if (event.cmd[7] == 0x02) {
                        tvWorkStatus.setText("重置当前错误继续工作");
                    }
                    if (Machine.status.contains("机器离线")) {
                        Machine.status.clear();
                        Machine.status.add("机器离线");
                    }
                    EventBus.getDefault().post(new WarningEvent(false, "警报已清除"));
                    break;
                case 0x4A:
                    tvWorkStatus.setText("温度标定");
                    break;
                case 0x4B:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("打开灯箱");
                    } else {
                        tvWorkStatus.setText("关闭灯箱");
                    }
                    break;
                case 0x51:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("碾米电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("碾米电机停止运行");
                    } else {
                        tvWorkStatus.setText("碾米电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x52:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("下米电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("下米电机停止运行");
                    } else {
                        tvWorkStatus.setText("下米电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x53:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("拉膜电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("拉膜电机停止运行");
                    } else {
                        tvWorkStatus.setText("拉膜电机运行" + event.cmd[9] + "s后停止");
                    }
                    break;
                case 0x54:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("封膜电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("封膜电机停止运行");
                    } else {
                        tvWorkStatus.setText("封膜电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x55:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("吹糠电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("吹糠电机停止运行");
                    } else {
                        tvWorkStatus.setText("吹糠电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x56:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("送谷电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("送谷电机停止运行");
                    } else {
                        tvWorkStatus.setText("送谷电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x57:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("送膜电机开始运行");
                    } else if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("送膜电机停止运行");
                    } else {
                        tvWorkStatus.setText("送膜电机运行" + (event.cmd[9] & 0xff) + "s后停止");
                    }
                    break;
                case 0x58:
                    if (event.cmd[7] == 0x00) {
                        tvWorkStatus.setText("精度电机停止运行");
                    } else if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("精度电机复位");
                    } else if (event.cmd[7] == 0x02) {
                        tvWorkStatus.setText("反转精度电机(左转)");
                    } else {
                        tvWorkStatus.setText("反转精度电机(右转)");
                    }
                    break;

                case 0x59:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("开门电机开到位");
                    } else if (event.cmd[7] == 0x02) {
                        tvWorkStatus.setText("开门电机运行" + (event.cmd[9] & 0xff) + "s后开到位");
                    } else if (event.cmd[7] == 0x03) {
                        tvWorkStatus.setText("开门电机开到位");
                    } else {
                        tvWorkStatus.setText("关门电机运行" + (event.cmd[9] & 0xff) + "s后关到位");
                    }
                    break;
                case 0x5A:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("开始纵封加热(100℃)");
                    } else {
                        tvWorkStatus.setText("停止纵封加热");
                    }
                    break;

                case 0x5B:
                    if (event.cmd[7] == 0x01) {
                        tvWorkStatus.setText("开始横封加热(100℃)");
                    } else {
                        tvWorkStatus.setText("停止横封加热");
                    }
                    break;

                default:
                    break;
            }
        }
        if (event.cmd[5] == 0x06 && isFilter) {
        } else {
            cmdDtoList.add(new MachineCmdDto(event.type, HexUtil.Bytes2HexString(event.cmd), mp.protocols.get(event.cmd[5])));
            adapter.notifyDataSetChanged();
            rvMachineCmd.scrollToPosition(adapter.getItemCount() - 1);
        }
    }

    @Override
    public void onItemClick(int position) {
        if (controlNames.get(position).equals("电机设置")) {
            ToastUtil.showLongToast(this, "当前处于手动模式，请勿强制关闭程序。");
        }
        switchFragment(fragmentMap.get(controlNames.get(position)));
    }

    private void switchFragment(Fragment f) {
        ft = fm.beginTransaction();
        if (accuracyF.isVisible()) {
            ft.hide(accuracyF);
        }

        if (millSetF.isVisible()) {
            ft.hide(millSetF);
        }

        if (garnerF.isVisible()) {
            ft.hide(garnerF);
        }

        if (temperatureF.isVisible()) {
            ft.hide(temperatureF);
        }

        if (weightF.isVisible()) {
            ft.hide(weightF);
        }

        if (motorF.isVisible()) {
            ft.hide(motorF);
        }

        if (warningF.isVisible()) {
            ft.hide(warningF);
        }

        if (machineTestF.isVisible()) {
            ft.hide(machineTestF);
        }

        if (doorSetF.isVisible()) {
            ft.hide(doorSetF);
        }

        if (modeF.isVisible()) {
            ft.hide(modeF);
        }

        if (violenceF.isVisible()) {
            ft.hide(violenceF);
        }

        if (coherentActionF.isVisible()) {
            ft.hide(coherentActionF);
        }

        if (powerF.isVisible()) {
            ft.hide(powerF);
        }

        ft.show(f);
        ft.commit();
    }

    @OnClick({R.id.btnClearWarningAndStay, R.id.btnClearWarningAndWorking, R.id.btnWorkStatus, R.id.btnClearPanelInfo, R.id.btnSend})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnClearWarningAndStay:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.停止当前工作并待机.code()));
                break;
            case R.id.btnClearWarningAndWorking:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.重置当前错误继续工作.code()));
                break;
            case R.id.btnWorkStatus:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.当前工作状态.code()));
                break;
            case R.id.btnClearPanelInfo:
                cmdDtoList.clear();
                adapter.notifyDataSetChanged();
                break;
            case R.id.btnSend: //手动发送命令
                String command = etCommand.getText().toString().trim();
                if (command.length() == 0) {
                    ToastUtil.show(MachineManagerA.this, "命令不能为空");
                } else {
                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(command));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        isFilter = isChecked;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.menu_com:
                startActivity(new Intent(MachineManagerA.this, ComSelectA.class));
                break;
            case R.id.menu_machine:
                startActivity(new Intent(MachineManagerA.this, MachineIdA.class));
                break;
            case R.id.menu_exit_time:
                startActivity(new Intent(MachineManagerA.this, ExitTimeA.class));
                break;
            case R.id.machine_pwd:
                startActivity(new Intent(MachineManagerA.this, ChangeMachinePwdA.class));
                break;
            case R.id.app_exit:
                uninstallApk();
                break;
            case R.id.upload_log:
                startActivity(new Intent(MachineManagerA.this, UploadLogA.class));
                break;
            case R.id.user_instruction:
                startActivity(new Intent(this, UserInstructionA.class));
                break;
            case R.id.error_code_instruction:
                startActivity(new Intent(this, ErrorCodeA.class));
                break;
            case R.id.net_stable_check:
                startActivity(new Intent(this, NetStableCheckA.class));
                break;
            case R.id.temp_curve:
                startActivity(new Intent(this, TempCurveA.class));
                break;
            case R.id.help_document:
                startActivity(new Intent(this, HelpDocA.class));
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (isTimerRunning) {
                    timer.cancel();
                    isTimerRunning = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                if (!isTimerRunning) {
                    timer.start();
                    isTimerRunning = true;
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        tvTitle.setText("单片机设置（" + MachineContainer.machineConfigDto.machineNo + "）");
        MachineContainer.isPay = false;
    }


    @Override
    protected void onPause() {
        super.onPause();
        MachineContainer.isPay = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAppUpdateEvent(AppUpdateEvent event) {
        appUpdateDto = event.appUpdateDto;
        if (appUpdateDto.getAppList().get(0).getVersion().compareTo(AppUtils.getVersionInfo(this)) > 0) {
            ivUpdateApp.setImageResource(R.drawable.icon_update_app_red);
            tvAppVersion.setText("有新版本可更新\n应用版本号N:".concat(AppUtils.getVersionInfo(this)));
        } else {
            ivUpdateApp.setImageResource(R.drawable.icon_update_app_gray);
            tvAppVersion.setText("应用版本号:".concat(AppUtils.getVersionInfo(this)));
        }
    }


    public void uninstallApk() {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:com.sgu6.sgu6_machine"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
